package certcrypto

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"os"
	"strings"
)

var (
	邮箱证书路径 = "ssl/acc/"
)

func IsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

func F获取私钥方法(mail string) (privateKey *ecdsa.PrivateKey, err error) {
	filepath := 邮箱证书路径 + mail + ".pem"
	privateKey, err = F读取私钥文件(filepath)
	if err != nil {
		privateKey, err = F获取私钥()
		if err != nil {
			return
		}
		if err = F私钥写入方法(privateKey, filepath); err != nil {
			return
		}
	}
	return
}

func F读取私钥文件(path string) (pri *ecdsa.PrivateKey, err error) {
	privateKeyPEM, err := os.ReadFile(path)
	if err != nil {
		return
	}

	// 解码PEM格式的私钥
	block, _ := pem.Decode(privateKeyPEM)

	//x509.MarshalECPrivateKey(
	pri, err = x509.ParseECPrivateKey(block.Bytes)
	// 解析私钥
	//privateKey1, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return
	}
	return
}

func F获取私钥() (privateKey *ecdsa.PrivateKey, err error) {
	privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	return
}

func F私钥写入方法(privateKey *ecdsa.PrivateKey, path string) (err error) {
	privateKeyBytes, err := x509.MarshalECPrivateKey(privateKey)
	if err != nil {
		return
	}

	// 创建PEM编码的块
	block := &pem.Block{
		Type:  "EC PRIVATE KEY",
		Bytes: privateKeyBytes,
	}

	// 创建PEM文件
	file, err := os.Create(path)
	if err != nil {
		return
	}
	defer file.Close()

	// 将PEM编码的块写入文件
	err = pem.Encode(file, block)
	if err != nil {
		return
	}
	return
}

func F获取DNS解析txt(domain, keyAuth string) (txt, str string) {
	keyAuthShaBytes := sha256.Sum256([]byte(keyAuth))
	// base64URL encoding without padding
	txt = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size])
	if strings.HasPrefix(domain, "*") {
		domain = domain[2:]
	}
	str = fmt.Sprintf("_acme-challenge.%s", domain)
	return
}
